/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BARelatedMaterialsTableViewController.m
//  redia-bapps-ios
//
//  Created by Henrik Lynbech on 08/10/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BARelatedMaterialsTableViewController.h"
#import "BARelatedMaterialCell.h"
#import "BARelatedMaterialsListViewController.h"
#import "BARelatedMaterialsData.h"
#import "BAReviewsViewController.h"
#import "BAAboutAuthorViewController.h"

#import "BALibrarySettings.h"

#ifdef BA_IMF_BUILD
#import "IMFLocationManager.h"
#import "IMFHomeAtViewController.h"
#endif

#import "BAHolding.h"


@interface BARelatedMaterialsTableViewController () {
    NSMutableArray* relatedMaterialCells;
    BARecord* record;
}

@property (nonatomic, strong) BARelatedMaterialCell* homeAtCell;

@end

@implementation BARelatedMaterialsTableViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
#ifdef BA_IMF_BUILD
    if ([[BALibrarySettings instance] isImfEnabled]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nearBranch) name:IMF_LOCATION_NEAR_BRANCH object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(leftBranch) name:IMF_LOCATION_LEFT_BRANCH object:nil];
        [[IMFLocationManager instance] startUpdatingLocation];
    }
#endif

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    /* this test is inadequate, since viewDidDisappear is also called when clicking on the tab switch to get the abstract
    if ([self.navigationController.viewControllers count] > 1) {
        UIViewController *secondFromTheTop = [self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 2];
        if (secondFromTheTop == self.parentViewController) {
            // This view may become visible again - don't cancel ongoing requests.
            return;
        }
    }
    */
    /* we can't cancel requests, since the spinners will spin indefinately
    [BARPCManager closeConnectionsForView:self];
     */
}

-(void)dealloc
{
    [BARPCManager closeConnectionsForView:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
#ifdef BA_IMF_BUILD
    [[IMFLocationManager instance] stopUpdatingLocation];
#endif
}

-(void)nearBranch{
    if ([self.homeAtCell isFetched] && self.availability != nil) {
#ifdef BA_IMF_BUILD
        NSString* branchId = [IMFLocationManager instance].nearestBranch;
        [self.homeAtCell showHighlighting:[self containsHoldingForBranchIdentifier:branchId inHoldings:self.availability.holdings]];
#endif
    }
}

-(void)leftBranch{
    [self.homeAtCell showHighlighting:NO];
}

-(BARelatedMaterialCell*)createCell {
    if (RD_IS_IPAD) {
        BARelatedMaterialCell* newcell = [[[NSBundle mainBundle] loadNibNamed:@"BARelatedMaterialCell_iPad" owner:self options:nil] objectAtIndex:0];
        return newcell;
        
    } else {
        return [[[NSBundle mainBundle] loadNibNamed:@"BARelatedMaterialCell_iPhone" owner:self options:nil] objectAtIndex:0];
    }
}

-(void)setRecord:(BARecord *)aRecord
{
    record = aRecord;
    
    if (RD_IS_IPAD) {
        if ([relatedMaterialCells count]>0) {
            for (BARelatedMaterialCell* oldcell in relatedMaterialCells) {
                [oldcell.contentView removeFromSuperview];
            }
        }
    }
    relatedMaterialCells = [NSMutableArray new];
    
    BARelatedMaterialCell* cell;
    int rowIndex = 0;

#ifdef BA_IMF_BUILD
    if ([BALibrarySettings instance].isImfEnabled && !record.isERessource) {
        cell = [self createCell];
        [cell setCategory:BARelatedMaterialsTableCellCategoryHomeAt rowNumber:rowIndex];
        [relatedMaterialCells addObject:cell];
        self.homeAtCell = cell;
        rowIndex++;
    }
#endif
    
    cell = [self createCell];
    [cell setCategory:BARelatedMaterialsTableCellCategoryReviews rowNumber:rowIndex];
    [relatedMaterialCells addObject:cell];
    rowIndex++;
    [BARPCManager getReviewsAsyncFromView:self
                              identifiers:@[record.identifier]
                              resultBlock:^(NSDictionary *result) {
                                  if (result && [result objectForKey:record.identifier]) {
                                      BAStandardResultObject *resultObject = [result objectForKey:record.identifier];
                                      if (resultObject && [resultObject.parsedData isKindOfClass:[NSArray class]] && [resultObject.parsedData count] > 0) {
                                          BARelatedMaterialsData *data = [BARelatedMaterialsData new];
                                          data.reviews = resultObject.parsedData;
                                          data.relationType = BA_RELATED_MATERIAL_TYPE_REVIEWS;
                                          cell.data = data;
                                          [cell setIsFetched:YES hasData:YES];
                                      }
                                      else {
                                          [cell setIsFetched:YES hasData:NO];
                                      }
                                  }
                                  else {
                                      [cell setIsFetched:YES hasData:NO];
                                  }
                              }
                               errorBlock:^(int errorCode, NSString *errorMessage) {
                                   DLog(@"error: getReviewsAsyncFromView");
                                   [cell setIsFetched:NO hasData:NO];
                               }];
    
    cell = [self createCell];
    [cell setCategory:BARelatedMaterialsTableCellCategoryAboutCreator rowNumber:rowIndex];
    [relatedMaterialCells addObject:cell];
    rowIndex++;
    [BARPCManager getAboutCreatorAsyncFromView:self
                                      creators:@[record.identifier]
                                   resultBlock:^(NSDictionary *result) {
                                       if (result && [result objectForKey:record.identifier]) {
                                           BAStandardResultObject *resultObject = [result objectForKey:record.identifier];
                                           if (resultObject && [resultObject.parsedData isKindOfClass:[NSDictionary class]] && [resultObject.parsedData count] > 0) {
                                               // Check that there is at least one valid author description in there.
                                               for (BAStandardResultObject *authorObj in [resultObject.parsedData allValues]) {
                                                   if (authorObj.result && [authorObj.parsedData isKindOfClass:[BAAboutCreator class]]) {
                                                       BAAboutCreator *aboutCreator = authorObj.parsedData;
                                                       if ([aboutCreator.name isEqualToString:@""] == NO && [aboutCreator.abstract isEqualToString:@""] == NO) {
                                                           BARelatedMaterialsData *data = [BARelatedMaterialsData new];
                                                           data.aboutAuthor = aboutCreator;
                                                           data.relationType = BA_RELATED_MATERIAL_TYPE_ABOUT_AUTHOR;
                                                           cell.data = data;
                                                           [cell setIsFetched:YES hasData:YES];
                                                           return;
                                                       }
                                                   }
                                               }
                                           }
                                       }
                                       [cell setIsFetched:YES hasData:NO];
                                   }
                                    errorBlock:^(int errorCode, NSString *errorMessage) {
                                        DLog(@"error: getAboutCreatorAsyncFromView");
                                        [cell setIsFetched:NO hasData:NO];
                                    }];
    
    cell = [self createCell];
    [cell setCategory:BARelatedMaterialsTableCellCategoryRelatedLoans rowNumber:rowIndex];
    [relatedMaterialCells addObject:cell];
    rowIndex++;
    [BARPCManager getRelatedLoansAsyncFromView:self
                                   identifiers:@[record.identifier]
                                   resultBlock:^(NSDictionary *result) {
                                       if (result && [result objectForKey:record.identifier]) {
                                           BAStandardResultObject *resultObject = [result objectForKey:record.identifier];
                                           if (resultObject && [resultObject.parsedData isKindOfClass:[NSArray class]] && [resultObject.parsedData count] > 0) {
                                               BARelatedMaterialsData *data = [BARelatedMaterialsData new];
                                               data.records = resultObject.parsedData;
                                               data.relationType = BA_RELATED_MATERIAL_TYPE_RELATED_LOANS;
                                               cell.data = data;
                                               [cell setIsFetched:YES hasData:YES];
                                           }
                                           else {
                                               [cell setIsFetched:YES hasData:NO];
                                           }
                                       }
                                       else {
                                           [cell setIsFetched:YES hasData:NO];
                                       }
                                   }
                                    errorBlock:^(int errorCode, NSString *errorMessage) {
                                        DLog(@"error: getRelatedLoansAsyncFromView");
                                        [cell setIsFetched:NO hasData:NO];
                                    }
     ];

    
    cell = [self createCell];
    [cell setCategory:BARelatedMaterialsTableCellCategoryMoreByCreator rowNumber:rowIndex];
    [relatedMaterialCells addObject:cell];
    rowIndex++;
    [BARPCManager getMoreByCreatorFromView:self
                                identifier:aRecord.identifier
                                    offset:0
                                     count:20
                                   filters:nil
                                    facets:nil
                               resultBlock:^(BASearchResult *results) {
                                   if (results!=nil && results.count>0) {
                                       [cell setIsFetched:YES hasData:YES];
                                       BARelatedMaterialsData *data = [BARelatedMaterialsData new];
                                       data.searchResult = results;
                                       data.relationType = BA_RELATED_MATERIAL_TYPE_MORE_BY_AUTHOR;
                                       data.identifier = aRecord.identifier;
                                       cell.data = data;
                                   } else {
                                       [cell setIsFetched:YES hasData:NO];
                                   }
                               }
     
                               errorBlock:^(int errorCode, NSString *errorMessage) {
                                   DLog(@"error: getMoreByCreatorFromView");
                                   [cell setIsFetched:NO hasData:NO];
                                   
                               }];
    
    cell = [self createCell];
    [cell setCategory:BARelatedMaterialsTableCellCategoryMoreInSameSeries rowNumber:rowIndex];
    [relatedMaterialCells addObject:cell];
    rowIndex++;
    if (record.moreInSameSeries) {
        [BARPCManager getMoreInSameSeriesAsyncFromView:self
                                            identifier:record.identifier
                                                offset:0
                                                 count:20
                                               filters:nil
                                                facets:nil
                                           resultBlock:^(BASearchResult *result) {
                                               if ([result count]>0) {
                                                   [cell setIsFetched:YES hasData:YES];
                                                   BARelatedMaterialsData *data = [BARelatedMaterialsData new];
                                                   data.searchResult = result;
                                                   data.relationType = BA_RELATED_MATERIAL_TYPE_MORE_IN_SERIES;
                                                   data.identifier = aRecord.identifier;
                                                   cell.data = data;
                                               } else {
                                                   [cell setIsFetched:YES hasData:NO];
                                               }
                                               
                                           } errorBlock:^(int errorCode, NSString *errorMessage) {
                                               DLog(@"error: getMoreInSameSeriesAsyncFromView");
                                               [cell setIsFetched:NO hasData:NO];
                                           }];

    } else {
        //record was marked as not having more in same series
        cell.userInteractionEnabled = NO;
        [cell setIsFetched:NO hasData:NO];

    }
    

    if (!RD_IS_IPAD) {
        [self.tableView reloadData];
        
    } else {
        //ipad
        
        if ([relatedMaterialCells count]>0) {
            CGFloat currX = 0;
            CGFloat cellwidth;
            if (relatedMaterialCells.count <= 5) {
                cellwidth = 685.0/[relatedMaterialCells count];
            } else{
                cellwidth = (685.0/5)-10;
            }
            
            for (BARelatedMaterialCell* newcell in relatedMaterialCells) {
                CGRect newrect = CGRectMake(currX, 0, cellwidth, 96);
                newcell.contentView.frame = newrect;
                [self.scrollViewIPad addSubview:newcell.contentView];
                
                [newcell.userClickButtonIPad removeTarget:self action:@selector(userClickedCellButtonIPad:) forControlEvents:UIControlEventTouchUpInside]; //avoid adding target twice
                [newcell.userClickButtonIPad addTarget:self action:@selector(userClickedCellButtonIPad:) forControlEvents:UIControlEventTouchUpInside];
                
                currX += cellwidth;
            }
            self.scrollViewIPad.contentSize = CGSizeMake(currX, 96);
        }
    }
    
}


-(void)setAvailability:(BAAvailability *)availability{
    _availability = availability;
    if (availability == nil || availability.homeAt.count == 0) {
        [self.homeAtCell setIsFetched:YES hasData:NO];
    }
    else if(availability.homeAt.count > 0){
#ifdef BA_IMF_BUILD
        [self.homeAtCell setIsFetched:YES hasData:YES];
        
        NSString* branchId = [IMFLocationManager instance].nearestBranch;
        [self.homeAtCell showHighlighting:[self containsHoldingForBranchIdentifier:branchId inHoldings:availability.holdings]];
#endif
    }
    
    
}

-(BOOL)containsHoldingForBranchIdentifier:(NSString*)branchId inHoldings:(NSArray*)holdings{
    if (branchId == nil || holdings == nil) {
        return NO;
    }
    for (BAHolding* holding in holdings) {
        if ([holding.branchId isEqualToString:branchId]) {
            return YES;
        }
    }
    return NO;
}

-(void)userClickedCellButtonIPad:(id)sender
{
    for (BARelatedMaterialCell* clickCell in relatedMaterialCells) {
        if (clickCell.userClickButtonIPad == sender) {
            if (clickCell.hasData) {
                [self userSelectedCell:clickCell];
            }
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [relatedMaterialCells count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [relatedMaterialCells objectAtIndex:indexPath.row];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DLog(@"clicked on row %d",indexPath.row);
    BARelatedMaterialCell* cell = (BARelatedMaterialCell*)[self.tableView cellForRowAtIndexPath:indexPath];
    [self userSelectedCell:cell];
}

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45.0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45.0;
}

-(void)userSelectedCell:(BARelatedMaterialCell*)cell {
    switch (cell.category) {
        case BARelatedMaterialsTableCellCategoryAboutCreator:
        {
            if (cell.isFetched && cell.hasData) {
                BAAboutAuthorViewController *vc = [[BAAboutAuthorViewController alloc] initWithNibName:@"BAAboutAuthorViewController" bundle:nil];
                vc.relatedMaterialsData = cell.data;
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        }
        case BARelatedMaterialsTableCellCategoryHomeAt:
        {
#ifdef BA_IMF_BUILD
            if (cell.isFetched && cell.hasData) {
                IMFHomeAtViewController* vc = [[IMFHomeAtViewController alloc] initWithNibName:@"IMFHomeAtViewController" bundle:nil];
                [vc setAvailability:self.availability];
                [self.navigationController pushViewController:vc animated:YES];
            }
#endif
            break;
        }
        case BARelatedMaterialsTableCellCategoryMoreByCreator:
        {
            if (cell.isFetched && cell.hasData) {
                BARelatedMaterialsListViewController *vc = [[BARelatedMaterialsListViewController alloc] initWithNibName:@"BARelatedMaterialsListViewController" bundle:nil];
                vc.headerText = @"Mere af samme forfatter";
                vc.relatedMaterialsData = cell.data;
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        }
        case BARelatedMaterialsTableCellCategoryMoreInSameSeries:
        {
            if (cell.isFetched && cell.hasData) {
                BARelatedMaterialsListViewController *vc = [[BARelatedMaterialsListViewController alloc] initWithNibName:@"BARelatedMaterialsListViewController" bundle:nil];
                vc.headerText = @"Mere i samme serie";
                vc.relatedMaterialsData = cell.data;
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        }
        case BARelatedMaterialsTableCellCategoryRelatedLoans:
        {
            if (cell.isFetched && cell.hasData) {
                BARelatedMaterialsListViewController *vc = [[BARelatedMaterialsListViewController alloc] initWithNibName:@"BARelatedMaterialsListViewController" bundle:nil];
                vc.headerText = @"Andre har også lånt";
                vc.relatedMaterialsData = cell.data;
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        }
        case BARelatedMaterialsTableCellCategoryReviews:
        {
            if (cell.isFetched && cell.hasData) {
                BAReviewsViewController *vc = [[BAReviewsViewController alloc] initWithNibName:@"BAReviewsViewController" bundle:nil];
                vc.relatedMaterialsData = cell.data;
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        }
    }
}

@end
